from collections import defaultdict
from openpyxl import load_workbook
from config import recharge_class, config_data, delete_empty_rows, create_excel

attendance_mapping = {
    '未参与':'×',
    '缺勤':'×',
    '事假':'○',
    '病假':'⊕',
    '早退':'□',
    '迟到':'△',
    '教师代签':'√',
    '已签':'√'
}

def read_data(filenames):
    result = defaultdict(list)
    for filename in filenames:
        wb = load_workbook(filename)
        sheet = wb['签到详情统计']
        max_row = sheet.max_row
        for i in range(5, max_row+1):
            _name = sheet.cell(i,1).value
            _id =  str(sheet.cell(i,2).value)
            _class =  sheet.cell(i,5).value
            if recharge_class:
                if _class in recharge_class:
                    teach_class = recharge_class.get(_class)
                else:
                    teach_class = recharge_class.get('other')
            else:
                teach_class = _class
            values = []
            for j in range(6, sheet.max_column + 1):
                value = sheet.cell(i,j).value
                values.append(attendance_mapping.get(value))
            if teach_class in result:
                result[teach_class].append((_id, _name, values))
            else:
                result[teach_class] = [(_id,_name, values)]
    return result

def write_data(file,_class, data): # data is a list with tuple
    workbook = load_workbook(file)
    sheet = workbook['考勤成绩']
    sheet.cell(1, 1).value = sheet.cell(1, 1).value.replace('semester', config_data['semester'])
    sheet.cell(2, 1).value = (sheet.cell(2, 1).value
                              .replace('class_name', _class)
                              .replace('course_name', config_data['course_name'])
                              .replace('teacher_name', config_data['teacher_name']))
    start_row = 4
    start_column = 4
    for i in range(len(data)):
        entry = data[i]
        row = start_row + i
        sheet.cell(row, 1).value = i + 1   #序号
        sheet.cell(row, 2).value = str(entry[0]).split('.')[0]   #学号
        sheet.cell(row, 3).value = entry[1]   #姓名
        values = entry[-1]
        # 由于read data的考勤是按时间从高到低排列，所以需要倒序输出
        for j in range(len(values),0,-1):
            value = values[j-1]
            sheet.cell(row, start_column + j -1).value = value
    delete_empty_rows(sheet, start_row)
    workbook.save(filename=file)



def do_task_attendance():
    result = read_data(config_data['read_file_path'])
    for _class, value in result.items():
        filename = create_excel(config_data['output_path'].format(_class))
        write_data(filename, _class, value)


if __name__ == '__main__':
    do_task_attendance()
